<?php

namespace app\components;

use Yii;
use yii\base\Event;
use yii\base\UserException;
use yii\web\ErrorHandler;
use yii\web\HttpException;
use yii\web\Response;

class BaseErrorHandler extends ErrorHandler {

    protected function renderException($exception) {
        if (Yii::$app->has('response')) {
            $response = Yii::$app->getResponse();
            $response->isSent = FALSE;
            $response->stream = NULL;
            $response->data = NULL;
            $response->content = NULL;
        } else {
            $response = new Response();
        }

        if (method_exists(Yii::$app->controller, 'renderException')) {
            return call_user_func([Yii::$app->controller, 'renderException'], $exception, $this);
        }

        $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
        if ($useErrorView && $this->errorAction !== NULL) {
            $result = Yii::$app->runAction($this->errorAction, compact('exception'));
            if ($result instanceof Response) {
                $response = $result;
            } else {
                $response->data = $result;
            }
            if (is_array($response->data)) {
                $response->format = Response::FORMAT_JSON;
            }
        } elseif ($response->format === Response::FORMAT_HTML) {
            if (YII_ENV_TEST || isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
                // AJAX request
                $response->data = '<pre>' . $this->htmlEncode($this->convertExceptionToString($exception)) . '</pre>';
            } else {
                // if there is an error during error rendering it's useful to
                // display PHP error in debug mode instead of a blank screen
                if (YII_DEBUG) {
                    ini_set('display_errors', 1);
                }
                $file = $useErrorView ? $this->errorView : $this->exceptionView;
                $response->data = $this->renderFile($file, [
                    'exception' => $exception,
                ]);
            }
        } elseif ($response->format === Response::FORMAT_RAW) {
            $response->data = $exception;
        } else {
            $response->data = $this->convertExceptionToArray($exception);
        }

        if ($exception instanceof HttpException) {
            $response->setStatusCode($exception->statusCode);
        } else {
            $response->setStatusCode(500);
        }

        $response->send();
    }

}